package com.wallet.admin.shiro;


import com.wallet.admin.feign.system.MenuFeignClient;
import com.wallet.admin.feign.system.RoleFeignClient;
import com.wallet.admin.feign.system.SysUserFeignClient;
import com.wallet.provider.model.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class MyAuthorizingRealm extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(MyAuthorizingRealm.class);

    @Autowired
    private SysUserFeignClient sysUserFeignClient;

    @Autowired
    private RoleFeignClient roleFeignClient;

    @Autowired
    private MenuFeignClient menuFeignClient;


    /**
     * 身份认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
     UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        logger.info("验证当前Subject时获取到token为：" + token.toString());
        //1. 查出是否有此用户
        SysUser hasUser = sysUserFeignClient.getSysUserByUsername(token.getUsername());
         /*String md5Pwd = new Md5Hash("123", "lucare",2).toString();
        if (hasUser != null) {
            // 若存在，将此用户存放到登录认证info中，无需自己做密码对比，Shiro会为我们进行密码对比校验
            List<Role> roles = roleService.getRoleByUserId(hasUser.getId());//获取用户角色
            List<Menu> menus = menuService.findPermissionByUid(hasUser.getId());//获取用户权限
            List<String> roleStrlist=new ArrayList<String>();////用户的角色集合
            List<String> perminsStrlist=new ArrayList<String>();//用户的权限集合
            for (Role role : roles) {
                roleStrlist.add(role.getName());
            }
            for (Menu menu : menus) {
                perminsStrlist.add(menu.getName());
            }
            hasUser.setRoleStrlist(roleStrlist);
            hasUser.setPerminsStrlist(perminsStrlist);
            Session session = SecurityUtils.getSubject().getSession();
            session.setAttribute("user", hasUser);//成功则放入session*/
        // 若存在，将此用户存放到登录认证info中，无需自己做密码对比，Shiro会为我们进行密码对比校验
        return new SimpleAuthenticationInfo(hasUser, hasUser.getPassword(), getName());
    }

    /**
     * 访问授权
     * @param principalCollection
     * @return
     */
    @Override
    public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }
}
